import serial
from time import sleep
import re

class socket:

    def __init__(self):
        self.ser = serial.Serial()
        self.ser.timeout = None
        self.ser.port = ""
        self.ser.baudrate = 115200


    def open(self, uartport, baunrate):
        self.ser.port = uartport
        self.ser.baudrate = baunrate

        self.ser.open()
        return self.ser.isOpen()

    def settimeout(self,timeout):
        self.ser.timeout = timeout

    def send(self, cmd):
        #print(cmd)
        self.ser.write(cmd)

    def revc(self, len):
        return self.ser.read(len)

    def inwaite(self):
        return self.ser.inWaiting()

    def revcline(self):
        bytes = 0
        resp = ""
        while True:
            data = self.ser.read(1)
            if (data == '\r' or data == '\n') and bytes == 0:
                continue

            resp = resp + data
            bytes = bytes + 1
            if bytes > 0 and resp[-2:] == "\r\n":
                return resp[0:-2]

            # if data == '\n':
            #     if bytes > 0 and resp[bytes - 1] == '\r':
            #         resp = resp + data
            #         return resp[0:-2]
            # else :
            #     resp = resp + data
            #     bytes= bytes + 1


    def write(self, data):
        self.ser.write(data)

    def read(self, size):
        return self.ser.read(size)

    def command(self, cmd, ack = ""):
        print("cmd: "+cmd)
        self.ser.write(cmd+"\r\n")
        response = self.revcline()
        self.ser.flushInput()
        print("response: "+response)

        if ack == "":
            return response
        else:
            print("ack: " + ack)

        #print "response == ack :" + (response == ack)

        if response == ack:
            return True
        else :
            return False

    def isIP(self, str):
        if str == "":
            return False

        p = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
        if p.match(str):
            return True
        else:
            return False

    def initnet(self, isReconnect):
        self.command("ATE0")
        self.command("AT+CNMP=13")
        self.command("AT+CIPMUX=0")
        while True:
            if self.command("AT+CGATT?","+CGATT: 1"):
                break
            else :
                print("GPRS NOT ATTACHED!")
                sleep(1)
                self.send("+++")
                sleep(1)
                self.command("AT")
                self.command("AT+CIPSHUT")

        self.command("AT+CIPMODE=1")
        sleep(1)
        #self.command("AT+CIPCCDG=5,2,1024,1,0,1460,50")
        #sleep(1)
        self.command("AT+CSTT=\"CMIOT\"")
        sleep(1)

        while(True):
            self.command("AT+CIICR","OK")
            ipaddr = self.command("AT+CIFSR")
            if self.isIP(ipaddr):
                print ipaddr
                return True
            else:
                sleep(1)
                self.send("+++")
                sleep(1)
                self.command("AT")
                self.command("AT+CIPSHUT")
                if isReconnect:
                    return self.initnet(isReconnect)
                else:
                    return False

        return False

    def connect(self, address):
        retry = 5
        ipaddr = address[0]
        port = address[1]

        cmd = "AT+CIPSTART=\"TCP\","+"\""+ipaddr+"\","+"\""+port+"\"\r\n"
        print(cmd)
        self.send(cmd)
        while retry > 0 :
            response = self.revcline()
            print response
            if response.find("CONNECT") > -1:
                return True
            retry = retry - 1
        return False

    def close(self):
        sleep(1)
        self.send("+++")
        sleep(1)
        self.command("AT")
        self.command("AT+CIPSHUT")
        return True

    def getaddrinfo(self, server, port):
        self.addr = (server, port)
        return self.addr



